package com.luom.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.luom.springbootinit.annotation.AuthCheck;
import com.luom.springbootinit.common.BaseResponse;
import com.luom.springbootinit.common.DeleteRequest;
import com.luom.springbootinit.common.ErrorCode;
import com.luom.springbootinit.common.ResultUtils;
import com.luom.springbootinit.constant.UserConstant;
import com.luom.springbootinit.exception.BusinessException;
import com.luom.springbootinit.exception.ThrowUtils;
import com.luom.springbootinit.model.dto.category.CategoryAddRequest;
import com.luom.springbootinit.model.dto.category.CategoryQueryRequest;
import com.luom.springbootinit.model.dto.category.CategoryUpdateRequest;
import com.luom.springbootinit.model.entity.Book;
import com.luom.springbootinit.model.entity.Category;
import com.luom.springbootinit.model.vo.BorrowRecordVO;
import com.luom.springbootinit.model.vo.CategoryVO;
import com.luom.springbootinit.service.BookService;
import com.luom.springbootinit.service.CategoryService;
import com.luom.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图书分类接口
 *
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @Resource
    private BookService bookService;

    // region 增删改查

    /**
     * 创建图书分类
     *
     * @param categoryAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addCategory(@RequestBody CategoryAddRequest categoryAddRequest) {
        ThrowUtils.throwIf(categoryAddRequest == null, ErrorCode.PARAMS_ERROR);
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddRequest, category);
        // 数据校验
        categoryService.validCategory(category, true);
        // 写入数据库
        boolean result = categoryService.save(category);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newCategoryId = category.getId();
        return ResultUtils.success(newCategoryId);
    }

    /**
     * 删除图书分类
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteCategory(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int id = deleteRequest.getId();
        // 判断是否存在
        Category oldCategory = categoryService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        // 判断该分类下是否有图书
        List<Book> bookList = bookService.list(new QueryWrapper<Book>().eq("categoryId", id));
        ThrowUtils.throwIf(!bookList.isEmpty(),ErrorCode.PARAMS_ERROR, "该分类下有图书，无法删除");
        // 操作数据库
        boolean result = categoryService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新图书分类（仅管理员可用）
     *
     * @param categoryUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCategory(@RequestBody CategoryUpdateRequest categoryUpdateRequest) {
        if (categoryUpdateRequest == null || categoryUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateRequest, category);
        // 数据校验
        categoryService.validCategory(category, false);
        // 判断是否存在
        int id = categoryUpdateRequest.getId();
        Category oldCategory = categoryService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = categoryService.updateById(category);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图书分类（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CategoryVO> getCategoryVOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Category category = categoryService.getById(id);
        ThrowUtils.throwIf(category == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(categoryService.getCategoryVO(category));
    }

    /**
     * 分页获取图书分类列表（仅管理员可用）
     *
     * @param categoryQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Category>> listCategoryByPage(@RequestBody CategoryQueryRequest categoryQueryRequest) {
        long current = categoryQueryRequest.getCurrent();
        long size = categoryQueryRequest.getPageSize();
        // 查询数据库
        Page<Category> categoryPage = categoryService.page(new Page<>(current, size),
                categoryService.getQueryWrapper(categoryQueryRequest));
        return ResultUtils.success(categoryPage);
    }

    /**
     * 分页获取图书分类列表（封装类）
     *
     * @param categoryQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<PageInfo<CategoryVO>> listCategoryVOByPage(@RequestBody CategoryQueryRequest categoryQueryRequest) {
        long current = categoryQueryRequest.getCurrent();
        long size = categoryQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
//        Page<Category> categoryPage = categoryService.page(new Page<>(current, size),
//                categoryService.getQueryWrapper(categoryQueryRequest));

        PageInfo<CategoryVO> page=categoryService.getCategoryVOPageL(categoryQueryRequest);

        // 获取封装类
        return ResultUtils.success(page);
    }
    // endregion

    /**
     * 获取分类map
     */
    /*@GetMapping("/list/page/all")
    public BaseResponse<Map<Integer,String>> listAllCategory() {

        List<Category> list = categoryService.list();
        Map<Integer,String> map=new HashMap<Integer,String>();
//        List<CategoryVO> categoryVOList = list.stream().map(item -> categoryService.getCategoryVO(item)).collect(Collectors.toList());
        for (Category category : list) {
            map.put(category.getId(),category.getName());
        }
        // 获取封装类
        return ResultUtils.success(map);
    }*/


    /*@GetMapping("/list/page/map")
    public BaseResponse<Map<Integer,Map<String, Object>>> listCategoryMap() {
        List<Category> list = categoryService.list();
        Map<Integer,Map<String, Object>> userMaps = new HashMap<>();
        for (Category category : list) {
            userMaps.put(category.getId(),Map.of("text",category.getName()));
        }
        // 获取封装类
        return ResultUtils.success(userMaps);
    }*/

    /**
     * 返回分类
     * @return
     */
    @GetMapping("/list/page/list")
    public BaseResponse<List<Category>> listCategory() {
        List<Category> categoryList = categoryService.list();
        // 获取封装类
        return ResultUtils.success(categoryList);
    }
}
